

import requests
from loguru import logger

from api.basic.parser import read_file
from config import ENV
from const import TOKEN_PATH


class Base:
    def send_request(self,data:dict):
        logger.info(f"接口请求信息为：{data}")
        r = requests.request(**data)
        logger.info(f"接口相应信息为：{r.text}")
        return r.json()

def request_hook(r,*args, **kwargs):
    logger.debug(f"接口请求信息为：{r.text}")
class RequestBase:

    def __init__(self):
        self._session = requests.Session()
        self._session.headers.update({'Content-Type': 'application/json', **read_file(str(TOKEN_PATH))})
        self._session.hooks['response'] = [request_hook]
        self._requests = self._session

    def _post(self,api_name,url: str,data):
        log_data = {
            "method": "POST",
            "url": url,
            "json": data
        }
        logger.debug(f"{api_name} -- 接口请求信息为:，{log_data}")
        response = self._requests.post(ENV.HOST + url,json=data)
        return response.json()

    def _put(self,api_name,url: str,data):
        log_data = {
            "method": "PUT",
            "url": url,
            "json": data
        }
        logger.debug(f"{api_name} -- 接口请求信息为:，{log_data}")
        response = self._requests.put(ENV.HOST + url,json=data)
        return response.json()

    def _delete(self,api_name,url: str):
        log_data = {
            "method": "DELETE",
            "url": url
        }
        logger.debug(f"{api_name} -- 接口请求信息为:，{log_data}")
        response = self._requests.delete(ENV.HOST + url)
        return response.json()

    def _get(self, api_name,url: str,params=None):
        log_data = {
            "method": "GET",
            "url": url,
            "params":params
        }
        logger.info(f"{api_name} -- 接口请求信息为:，{log_data}")
        response = self._requests.get(ENV.HOST + url,params=params)
        return response.json()